import { Dropdown, DropdownItem } from "@/ui/Dropdown/Dropdown";
import cls from "@/styles/components/CreateUser/RoleSelector.module.scss";
import React, { useEffect, useMemo, useState } from "react";
import { UserI } from "@/models/user";
import { Icon } from "@/ui/Icons/Icon";
import cn from "classnames";
import { useSpecialization, useSpecializationType } from "@/api/specialization";
import { SpecializationI } from "@/models/specialization";
import { OptionI } from "@/models/common";

type Props = {
  setSpec: (v: OptionI) => void;
};

export const SpecSelector = ({ setSpec }: Props) => {
  const [specDropdownOpen, setSpecDropdownOpen] = useState(false);
  const [selected, setSelected] = useState<OptionI>(null);

  const [, specData] = useSpecializationType();
  const options = useMemo(() => {
    if (!specData) return [];
    return specData.map((s) => {
      return { id: s.id, name: s.specialization };
    });
  }, [specData]);
  useEffect(() => {
    if (!options) return;
    setSelected(options[0]);
  }, [specData]);

  useEffect(() => {
    if (!selected) return;
    setSpec(selected);
  }, [selected]);

  const toggleOpen = () => {
    setSpecDropdownOpen(!specDropdownOpen);
  };

  return (
    <div className={cls.root}>
      <div className={cls.label}>Модальность</div>
      <div className={cls.valueBox} onClick={() => toggleOpen()}>
        <div className={cls.value}>{selected?.name}</div>
        <button
          type="button"
          onClick={() => toggleOpen()}
          className={cls.arrow}
        >
          <Icon name="arrow" />
        </button>
      </div>
      <Dropdown
        isOpen={specDropdownOpen}
        close={() => setSpecDropdownOpen(false)}
        parentCls={cls.root}
        fullWidth
      >
        {options?.map((o) => {
          return (
            <DropdownItem key={o.id}>
              <button
                type="button"
                className={cn(cls.option, {
                  [cls.selected]: o.id === selected?.id,
                })}
                onClick={() => {
                  setSelected(o);
                  setSpecDropdownOpen(false);
                }}
              >
                {o.name}
              </button>
            </DropdownItem>
          );
        })}
      </Dropdown>
    </div>
  );
};
